# code:utf8
import json
import logging
from datetime import datetime

from pyquery import PyQuery
from scrapy.utils.project import get_project_settings
from zc_core.model.items import *
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_number, parse_timestamp, parse_time, parse_date
from zc_core.util.deadline_filter import DeadlineFilter
from zc_core.util.encrypt_util import md5
from zc_core.util.order_deadline_filter import OrderItemFilter
from zc_core.util.sku_id_parser import convert_id2code

logger = logging.getLogger('rule')
order_filter = OrderItemFilter()
inq_deadline_filter = DeadlineFilter(get_project_settings().get('INQUIRY_DEADLINE_DAYS', 7))


# 解析catalog列表
def parse_catalog(response):
    settings = get_project_settings()
    white_list = settings.get('CATALOG_WHITE_LIST', [])
    cats = list()
    rows = json.loads(response.text)
    if rows:
        for row in rows:
            cat1_id = row.get('innercode')
            if cat1_id in white_list:
                cat1 = _build_catalog(row, '', 1)
                cats.append(cat1)
                sub2 = row.get('childs')
                if sub2:
                    for child2 in sub2:
                        cat2 = _build_catalog(child2, cat1, 2)
                        cats.append(cat2)
                        sub3 = child2.get('childs')
                        if sub3:
                            for child3 in sub3:
                                cat3 = _build_catalog(child3, cat2, 3)
                                cats.append(cat3)

    return cats


def _build_catalog(data, p_cat, level):
    cat = Catalog()
    cat['catalogId'] = str(data.get('innercode'))
    cat['catalogName'] = str(data.get('category_name'))
    if p_cat:
        cat['parentId'] = p_cat.get('catalogId')
    else:
        cat['parentId'] = ''
    cat['level'] = level
    if cat['level'] == 3:
        # 1、是
        cat['leafFlag'] = 1
    else:
        # 2、否
        cat['leafFlag'] = 2
    cat['linkable'] = 1

    return cat


# 解析总页数
def parse_sku_pages(response):
    js = json.loads(response.text)
    if js and 'result' in js:
        total = js.get('result', {}).get('pageTotal', 0)
        return total

    return 0


# 解析sku列表
def parse_sku(response):
    sku_list = list()
    js = json.loads(response.text)
    if js and 'result' in js:
        rows = js.get('result', {}).get('data', [])
        if rows:
            for row in rows:
                sku_id = str(row.get('skuid'))
                # sale_price = row.get('tax_price')
                # if sale_price <= 0:
                #     logger.info('下架：%s' % sku_id)
                #     continue
                sku = Sku()
                sku['skuId'] = sku_id
                sku['supplierId'] = str(row.get('supplier_id'))
                # sku['salePrice'] = sale_price
                # sku['originPrice'] = parse_number(row.get('open_taxprice'))
                sku_list.append(sku)

    return sku_list


def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')

    result = ItemData()
    js = json.loads(response.text)
    if js and 'data' in js and js.get('data', None):
        data = js.get('data')
        # -------------------------------------------------
        result['batchNo'] = batch_no
        result['skuId'] = sku_id
        result['skuName'] = data.get('title', '')
        result['skuImg'] = data.get('main_picture', {}).get('uri_large', '')
        result['catalog1Id'] = ''
        result['catalog1Name'] = ''
        result['catalog2Id'] = ''
        result['catalog2Name'] = ''
        result['catalog3Id'] = data.get('category', {}).get('innercode', '')
        result['catalog3Name'] = data.get('category', {}).get('category_name', '')
        result['salePrice'] = parse_number(data.get('tax_price', '-1'))
        result['originPrice'] = parse_number(data.get('open_taxprice', result['salePrice']))
        result['unit'] = data.get('unit')
        br_name = data.get('brand', {}).get('brand_name', '')
        if br_name:
            result['brandId'] = md5(br_name)
            result['brandName'] = br_name
        sp_id = data.get('supplier', {}).get('supplier_id', '')
        if sp_id:
            result['supplierId'] = str(sp_id)
            result['supplierName'] = data.get('supplier', {}).get('supplier_name', '')

        attr_groups = data.get('specifications', {}).get('groups', [])
        if attr_groups:
            for group in attr_groups:
                group_items = group.get('group_items', [])
                for kv in group_items:
                    if kv and kv.get('key', '') == '编码':
                        # 供应商商品编码
                        sp_sku_id = kv.get('value', '')
                        if sp_sku_id:
                            result['supplierSkuId'] = sp_sku_id
                            sp_name = result['supplierName']
                            plat_code = None
                            if '得力' in sp_name:
                                plat_code = 'deli'
                            result['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)

                group_items2 = group.get('group_items2', [])
                for kv in group_items2:
                    if kv and kv.get('key', '') == '规格':
                        # 品牌型号
                        result['brandModel'] = kv.get('value', '')

        result['genTime'] = datetime.utcnow()
        # -------------------------------------------------

    return result


# 解析ItemData
def parse_order(response):
    pages = list()
    js = json.loads(response.text)
    if js and 'dataTables' in js:
        rows = js.get('dataTables').get('middlemanPurOrderDataTable').get('rows')
        for row in rows:
            if 'status' in row and row.get('status') == 'nrm' and 'data' in row:
                data = row.get('data')
                order_time = parse_timestamp(data.get('orderTime', ''))
                # 采集截止
                if order_filter.to_save(order_time):
                    order = Order()
                    order['id'] = str(data.get('id'))
                    order['orderCode'] = data.get('orderno')
                    order['totalPrice'] = parse_number(data.get('totalMoney'))
                    order['orderDept'] = data.get('nyMiddlemanName')
                    order['supplierId'] = str(data.get('enterpriseId'))
                    order['supplierName'] = data.get('EnterpriseName')
                    order['batchNo'] = time_to_batch_no(order_time)
                    order['orderTime'] = order_time
                    order['genTime'] = datetime.utcnow()
                    pages.append(order)

    return pages


def parse_order_item(response):
    meta = response.meta
    order = meta.get('order')
    order_id = order.get('id')

    items = list()
    order_info = None
    consignee = None
    js = json.loads(response.text)
    if js and 'dataTables' in js and order_id:
        info_rows = js.get('dataTables').get('middlemanPurOrderDataTable').get('rows')
        if info_rows and len(info_rows):
            main_row = info_rows[0]
            order_info = main_row.get('data')
            consignee = json.loads(order_info.get('consignee_info'))
        rows = js.get('dataTables').get('middlemanPurOrderDetailDataTable').get('rows')
        if rows and len(rows) and order_info:
            order_time = parse_timestamp(order_info.get('orderTime', ''))
            for row in rows:
                if 'status' in row and row.get('status') == 'nrm' and 'data' in row:
                    data = row.get('data')
                    item = OrderItem()
                    item['id'] = '{}_{}'.format(order_id, data.get('id'))
                    item['orderId'] = order_id
                    item['orderCode'] = order_info.get('orderno')
                    item['skuId'] = data.get('skuValue')
                    count = data.get('quantity')
                    tax_price = data.get('taxPrice')
                    item['count'] = count
                    item['amount'] = count * tax_price
                    if consignee:
                        item['orderUser'] = consignee.get('name') + ' ' + consignee.get('mobile')
                    item['orderDept'] = data.get('deliverAddress')
                    item['orderTime'] = order_time
                    item['supplierId'] = str(order.get('supplierId'))
                    item['supplierName'] = order.get('supplierName')
                    item['batchNo'] = time_to_batch_no(order_time)
                    items.append(item)

    return items


# =========================
# 解析ItemData
def parse_inquiry_list(response):
    inq_list = list()
    rs = json.loads(response.text)
    if rs and rs.get('rows', []):
        rows = rs.get('rows', [])
        for row in rows:
            publish_time = parse_time(row.get('PUBLISH_TIME')[0:19])
            if inq_deadline_filter.filter(publish_time):
                inq = Inquiry()
                inq['_id'] = row.get('TENDER_ID')
                inq['projectCode'] = row.get('TENDERNO')
                inq['projectId'] = row.get('TENDER_ID')
                inq['projectName'] = row.get('TENDERNAME')
                inq['buyerOrg'] = row.get('BUYERS_NAME')
                inq['buyerDept'] = row.get('BUYERS_DEPART_NAME')
                inq['publishTime'] = publish_time
                inq['deadlineTime'] = parse_time(row.get('RULE_SUBMIT_END_DATE')[0:19])
                inq['status'] = row.get('HAS_BID', '0')
                inq_list.append(inq)
    return inq_list


# 解析BidItemDetail
def parse_inquiry_item(response):
    meta = response.meta
    project_id = meta.get('projectId')
    project_code = meta.get('projectCode')
    jpy = PyQuery(response.text)

    inq = Inquiry()
    inq['projectId'] = project_id
    inq['projectCode'] = project_code
    inq['projectName'] = jpy('label.short:contains("采购名称：")').parent().text().replace('采购名称：', '').strip()
    inq['buyerName'] = jpy('label.short:contains("采购员：") + span').text()
    inq['buyerPhone'] = jpy('label.short:contains("办公电话：") + span').text()
    inq['buyerOrg'] = jpy('label.short:contains("采购组织：") + span').text()
    inq['buyerDept'] = jpy('label.short:contains("采购部门：") + span').text()
    inq['currency'] = jpy('label.short:contains("币种：") + span').text()
    inq['taxType'] = jpy('label.short:contains("税项：") + span').text()
    inq['taxRate'] = jpy('label.short:contains("税率：")').parent().text().replace('税率：', '').strip()
    inq['publishTime'] = parse_time(jpy('label.short:contains("发布时间：") + span').text())
    inq['validityDate'] = parse_date(jpy('label.short:contains("报价有效期：")').parent().text().replace('报价有效期：', '').strip())
    inq['deadlineTime'] = parse_time(jpy('label.short:contains("报价截止时间：") + span').text(), fmt='%Y-%m-%d %H:%M')

    inq['address'] = jpy('label.short:contains("送货地址：")').parent().text().replace('送货地址：', '').strip()
    inq['carriageIn'] = jpy('label.short:contains("是否含运费：")').parent().text().replace('是否含运费：', '').strip()
    notes = jpy('label.short:contains("备注：") + textarea')
    if notes and notes[0].text:
        inq['notes'] = notes.text()
    inq['inquiryType'] = jpy('label.short:contains("询价方式：") + span').text()
    inq['quoteType'] = jpy('label.short:contains("报价方式：") + span').text()
    inq['payType'] = jpy('label.short:contains("付款方式：") + span').text()
    inq['status'] = jpy('label.short:contains("状态：") + span').text()

    # att_list = list()
    # attach_ids = jpy('div.uploadFile')
    # for att in attach_ids.items():
    #     att_list.append({
    #         'fileId': att.attr('relationval'),
    #         'url': 'http://mall.cdtbuy.cn/AttachmentController.do?method=downLoadFile&objId=8ae1bcf172c83c93017366f483d64f2d',
    #     })
    # inq['attachments'] = att_list

    item_list = list()
    trs = jpy('table#SubProjectList tbody tr')
    for tr in trs.items():
        item = InquiryItem()
        tds = tr('td')
        if tds and len(tds) >= 10:
            item['_id'] = tds.eq(1).text()
            item['itemId'] = tds.eq(1).text()
            item['itemCode'] = tds.eq(1).text()
            item['projectCode'] = project_code
            item['itemName'] = tds.eq(4).text()
            item['itemType'] = tds.eq(2).text()
            item['unit'] = tds.eq(5).text()
            item['count'] = tds.eq(6).text()
            item['deliveryTime'] = parse_date(tds.eq(7).text())
            item['notes'] = tds.eq(8).text()
            item['attachments'] = tds.eq(9).text()
            item['sortNum'] = tds.eq(0).text()
            item['publishTime'] = inq['publishTime']
            item_list.append(item)

    return inq, item_list
